/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI;

import DAO.CustomerDAO;
import GUI.Components.IToolbarPerformEvent;
import GUI.Components.JErrorProvider;
import GUI.Components.ToolbarEvent;
import POJO.Customer;
import Util.DataAccessUtil;
import Util.GuiUtil;
import Util.MsgUtil;
import java.util.ArrayList;
import java.util.List;
import javax.swing.table.AbstractTableModel;

/**
 *
 * @author Nguyễn Thi Mỷ Diện (1140214)
 */
public class FrmCustomer extends javax.swing.JInternalFrame {

    /**
     * Creates new form FrmCustomer
     */
    private JErrorProvider jErrorControl;
    private List<Customer> listCustomers = null;
    private final String ER_EMPTY_INPUT_CUSTOMER = "Bạn chưa nhập tên danh mục!";
    private final String ER_INSERT_CUSTOMER = "Có lỗi trong quá trình thêm!";
    private final String ER_UPDATE_CUSTOMER = "Có lỗi trong quá trình cập nhật!";
    private final String ER_DELETE_CUSTOMER = "Có lỗi trong quá trình xóa!";
     private org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(this.getClass().getName());
    
    public FrmCustomer() {
        initComponents();
        
        initComponents();        
        jErrorControl = new JErrorProvider();
       
        tbCustomer.setModel(new CustomerModelTable(new ArrayList()));
        this.loadTable();
        refreshControl(false);
        this.userControlForm();       
    }
     
    private void loadTable() {
        try {
            listCustomers = CustomerDAO.getListCustomer();
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex.fillInStackTrace());
            return;
        }
        getCustomerModelTable().setList(listCustomers);
    }
     
    private void userControlForm(){
        toolbarCustomer.addEventPerformClick(new IToolbarPerformEvent() {

            @Override
            public void performEventAdd(ToolbarEvent evt) {
               // refreshControl(true);
                txtCustomerName.setText("");     
                txtCustomerAddress.setText(""); 
                txtCustomerEmail.setText("");     
                txtCustomerPhone.setText(""); 
                
            }

            @Override
            public void performEventEdit(ToolbarEvent evt) {
                refreshControl(true);
            }

            @Override
            public void performEventDelete(ToolbarEvent evt) {
                if(tbCustomer.getSelectedRowCount() < 1)
                    return;
               
                Customer customer = 
                        getCustomerModelTable().getItem(tbCustomer.getSelectedRow());
               try {
                        DataAccessUtil.delete(customer);
                        MsgUtil.info("Xóa khách hàng "+customer.getName()+" thành công!");
                        loadTable();
                    } catch (Exception e) {
                        log.error(e.getMessage(), e.fillInStackTrace());
                        MsgUtil.error(ER_DELETE_CUSTOMER,e.getMessage());
                    }
            }

            @Override
            public void performEventSave(ToolbarEvent evt) {
                jErrorControl.clear();
                if (txtCustomerName.getText().isEmpty()) {
                    jErrorControl.setError(txtCustomerName, ER_EMPTY_INPUT_CUSTOMER);
                    evt.setIsError(true);
                    return;
                }
                Customer customer = new Customer();
                customer.setName(txtCustomerName.getText());
                customer.setAddress(txtCustomerAddress.getText());
                customer.setEmail(txtCustomerEmail.getText());
                customer.setPhone(txtCustomerPhone.getText());
                
                if (evt.isIsAdding()) {
                    try {
                        DataAccessUtil.insert(customer);
                        MsgUtil.info("Thêm khách hàng "+customer.getName()+" thành công!");
                        loadTable();
                    } catch (Exception e) {
                        log.error(e.getMessage(), e.fillInStackTrace());
                        MsgUtil.error(ER_INSERT_CUSTOMER,e.getMessage());
                    }
                } else if (evt.isIsUpdating()) {
                    int id = (int) getCustomerModelTable()
                                .getValueAt(tbCustomer.getSelectedRow(), 0);
                    customer.setId(id); 
                    try {
                        DataAccessUtil.update(customer);
                        MsgUtil.info("Cập nhật khách hàng thành công!");
                        loadTable();
                    } catch (Exception e) {
                        log.error(e.getMessage(), e.fillInStackTrace());
                         MsgUtil.error(ER_UPDATE_CUSTOMER,e.getMessage());
                    }
                }
                refreshControl(false);
            }

            @Override
            public void performEventCancel(ToolbarEvent evt) {
                throw new UnsupportedOperationException("Not supported yet.");
            }

            @Override
            public void performEventRefresh(ToolbarEvent evt) {
                throw new UnsupportedOperationException("Not supported yet.");
            }

            @Override
            public void performEventClose(ToolbarEvent evt) {
                throw new UnsupportedOperationException("Not supported yet.");
            }
     
        });
    }
    
     private CustomerModelTable getCustomerModelTable(){
        return (CustomerModelTable) tbCustomer.getModel();
    }
     
     //<editor-fold defaultstate="collapsed" desc="Refresh, cập nhập lại trạng thái controls">
    private void refreshControl(boolean editing){
        //txtCustomerId.setEnabled(editing);
        txtCustomerName.setEnabled(editing);
        txtCustomerAddress.setEnabled(editing);
        txtCustomerEmail.setEnabled(editing);
        txtCustomerPhone.setEnabled(editing);
    }
    //</editor-fold>

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tbCustomer = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        txtCustomerAddress = new javax.swing.JTextField();
        txtCustomerName = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        txtCustomerEmail = new javax.swing.JTextField();
        txtCustomerPhone = new javax.swing.JTextField();
        toolbarCustomer = new GUI.Components.Toolbar();

        setTitle("Khách hàng");

        tbCustomer.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Mã khách hàng", "Tên khách hàng", "Địa chỉ", "Email", "Điện thoại"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.String.class, java.lang.String.class, java.lang.Object.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tbCustomer.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tbCustomerMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tbCustomer);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Thông tin khách hàng", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 14))); // NOI18N
        jPanel1.setToolTipText("");

        jLabel1.setText("Tên khách hàng:");

        jLabel2.setText("Địa chỉ:");

        txtCustomerAddress.setName("jTextField_DiaChi");
        txtCustomerAddress.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtCustomerAddressActionPerformed(evt);
            }
        });

        txtCustomerName.setName("jTextField_TenCuaHang");
        txtCustomerName.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtCustomerNameActionPerformed(evt);
            }
        });

        jLabel4.setText("Điện thoại:");

        jLabel5.setText("Email:");

        txtCustomerEmail.setName("jTextField_TenCuaHang");
        txtCustomerEmail.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtCustomerEmailActionPerformed(evt);
            }
        });

        txtCustomerPhone.setName("jTextField_TenCuaHang");
        txtCustomerPhone.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtCustomerPhoneActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(txtCustomerName)
                    .addComponent(txtCustomerAddress, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel4)
                    .addComponent(jLabel5))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(txtCustomerEmail, javax.swing.GroupLayout.DEFAULT_SIZE, 180, Short.MAX_VALUE)
                    .addComponent(txtCustomerPhone))
                .addGap(60, 60, 60))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(txtCustomerName)
                            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(txtCustomerAddress)
                            .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtCustomerEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtCustomerPhone, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 684, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addComponent(toolbarCustomer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 362, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(toolbarCustomer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 265, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void txtCustomerNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtCustomerNameActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtCustomerNameActionPerformed

    private void txtCustomerAddressActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtCustomerAddressActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtCustomerAddressActionPerformed

    private void txtCustomerPhoneActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtCustomerPhoneActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtCustomerPhoneActionPerformed

    private void txtCustomerEmailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtCustomerEmailActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtCustomerEmailActionPerformed

    private void tbCustomerMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbCustomerMouseClicked
       Customer customer = getCustomerModelTable().getItem(tbCustomer.getSelectedRow()); 
       //txtCustomerId.setText(customer.getId());
       txtCustomerName.setText(customer.getName());
       txtCustomerAddress.setText(customer.getAddress());
       txtCustomerEmail.setText(customer.getEmail());
       txtCustomerPhone.setText(customer.getPhone());
    }//GEN-LAST:event_tbCustomerMouseClicked

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tbCustomer;
    private GUI.Components.Toolbar toolbarCustomer;
    private javax.swing.JTextField txtCustomerAddress;
    private javax.swing.JTextField txtCustomerEmail;
    private javax.swing.JTextField txtCustomerName;
    private javax.swing.JTextField txtCustomerPhone;
    // End of variables declaration//GEN-END:variables
}
//<editor-fold defaultstate="collapsed" desc="Customer model table">
class CustomerModelTable extends AbstractTableModel {

    private static final String[] columnNames = {"Mã khách hàng", "Tên khách hàng", "Địa chỉ", "Email", "Điện thoại"};
    private List<Customer> list;

    public CustomerModelTable(List<Customer> list) {
        this.list = list;
    }

    public List<Customer> getList() {
        return this.list;
    }
    public Customer getItem(int rowIndex){
        return this.list.get(rowIndex);
    }
    public void setList(List<Customer> list) {
        this.list = list;
        fireTableDataChanged();
    }

    public void removeAllElement() {
        this.list.clear();
        fireTableDataChanged();
    }

    public void addElement(Customer e) {
        // Adds the element in the last position in the list
        list.add(e);
        fireTableRowsInserted(list.size() - 1, list.size() - 1);
    }

    public void removeElement(int rowIndex) {
        list.remove(rowIndex);
        fireTableRowsDeleted(rowIndex, rowIndex);
    }

    @Override
    public int getRowCount() {
        return list.size();
    }

    @Override
    public int getColumnCount() {
        return columnNames.length;
    }

    @Override
    public String getColumnName(int index) {
        return columnNames[index];
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        switch (columnIndex) {
            case 0:
                return list.get(rowIndex).getId();
            case 1:
                return list.get(rowIndex).getName();
            case 2:
                return list.get(rowIndex).getAddress();
            case 3:
                return list.get(rowIndex).getEmail();
            case 4:
                return list.get(rowIndex).getPhone();
        }
        return null;
    }
}
//</editor-fold>

